import axios from 'axios'
import JSONBig from 'json-bigint'
import store from '@/store'
import router from '@/router/index.js'
const instance = axios.create({
  baseURL: 'http://ttapi.research.itcast.cn/',
  transformResponse: [
    function (data) {
      try {
        return JSONBig.parse(data)
      } catch (err) {
        return data
      }
    }
  ]
})
instance.interceptors.request.use(function (config) {
  if (store.state.user.token) {
    config.headers.Authorization = 'Bearer ' + store.state.user.token
  }
  return config
}, function (error) {
  return Promise.reject(error)
}
)
instance.interceptors.response.use(function (response) {
  try {
    return response.data.data
  } catch (err) {
    return response.data
  }
}, function (error) {
  if (error.response.status === 401) {
    router.push('/login')
    return new Promise(function () {})
  }
  return Promise.reject(error)
})
export default instance
